package com.raft.core.log.entry;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.com.caucho.hessian.io.HessianOutput;
import com.raft.core.node.NodeEndpoint;
import com.raft.core.node.NodeId;

/**移除节点时的日志条目
 * @author Ziroom
 *
 */
public class RemoveNodeEntry extends GroupConfigEntry {

    /**
     * 移除对象
     */
    private final NodeId nodeToRemove;

    public RemoveNodeEntry(int index, int term, Set<NodeEndpoint> nodeEndpoints, NodeId nodeToRemove) {
        super(KIND_REMOVE_NODE, index, term, nodeEndpoints);
        this.nodeToRemove = nodeToRemove;
    }

    @Override
	public Set<NodeEndpoint> getResultNodeEndpoints() {
        return getNodeEndpoints().stream()
                .filter(c -> !c.getId().equals(nodeToRemove))
                .collect(Collectors.toSet());
    }

    /**获取移除对象
     * @return
     */
    public NodeId getNodeToRemove() {
        return nodeToRemove;
    }

    @Override
    public byte[] getCommandBytes() {
    	ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
    	HessianOutput hessianOutput = new HessianOutput(byteOutput);
        try {
			hessianOutput.writeObject(this);
		} catch (IOException e) {
			e.printStackTrace();
		}
        return byteOutput.toByteArray();
    }

    @Override
    public String toString() {
        return "RemoveNodeEntry{" +
                "index=" + index +
                ", term=" + term +
                ", nodeEndpoints=" + getNodeEndpoints() +
                ", nodeToRemove=" + nodeToRemove +
                '}';
    }

}
